package org.videopractice.media;

import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.view.Surface;

import java.io.IOException;


public class RecordScreen {

    private final MediaProjectionManager mediaProjectionManage;

    private MediaProjection mediaProjection;

    private VirtualDisplay virtualDisplay;
    private MediaEncoder encoder;

    public RecordScreen(Context context) {
        mediaProjectionManage = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
    }

    public boolean checkReady() {
        return mediaProjection != null;
    }

    public Intent requestRecording() {
        return mediaProjectionManage != null ? mediaProjectionManage.createScreenCaptureIntent() : null;
    }

    public void getMediaProjection(int resultCode, Intent resultData) {
        mediaProjection = mediaProjectionManage.getMediaProjection(resultCode, resultData);
    }

    public void createVirtualDisplay(int width, int height) {
        try {
            encoder = new MediaEncoder(new ScreenLive().startLiving()).preReady(width, height);
            Surface surface = encoder.createInputSurface();
            //实例化VirtualDisplay,这个类的主要作用是用来获取屏幕信息并保存在里。
            virtualDisplay = mediaProjection.createVirtualDisplay("ScreenRecord", width, height, 1,
//                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null);
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, surface, null, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized void startCapture(int width, int height) {
        createVirtualDisplay(width, height);
        encoder.startEncode();
    }

    public void stopCapture() {
        encoder.stopEncode();
        virtualDisplay.release();
    }




}
